<template>
    <div class="app-container">

        <el-card shadow="always">
            <div>
                <div class="flex justify-between align-center">
                    <div>
                        <p><span style="color:#fd2f2f;">当前美国时区:(-8)：{{ us_time | parseTime('y-m-d h:i:s 星期a') }}</span>
                        <!-- <span style="color:#fd2f2f;">,当前欧洲时区:(+2)：{{ eur_time | parseTime('y-m-d h:i:s 星期a') }}</span> -->
                        </p>
                    </div>
                </div>
            </div>

            <el-form v-show="showSearch" ref="queryForm" label-width="120px" @keyup.enter.native="submitSearch" @submit.native.prevent>
                <el-row>
                    <el-col :md="12" :sm="12" style="margin-bottom: 10px;">
                        <el-form-item label="时间:">
                            <el-radio-group @change="day_change" v-model="saleSearch.dateType" size="small" class="mr5">
                                <el-radio-button :label="0">今天</el-radio-button>
                                <el-radio-button :label="1">昨天</el-radio-button>
                                <el-radio-button :label="2">最近7天</el-radio-button>
                                <el-radio-button :label="3">本月</el-radio-button>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :md="12" :sm="12" style="margin-bottom: 10px;">
                        <el-form-item label="店铺:">
                            <template>
                                <el-select
                                    v-model="saleSearch.site_id"
                                    filterable
                                    multiple
                                    @change="select_change"
                                    collapse-tags
                                    style="min-width:300px"
                                    placeholder="选择店铺">
                                        <el-option
                                            v-for="item in site_arr"
                                            :key="item.id"
                                            :label="item.name"
                                            :value="item.id"
                                            >
                                            <span style="float: left">{{ item.name }}</span>
                                            <span style="float: right; color: #8492a6; font-size: 13px">{{ item.region }}</span>
                                        </el-option>
                                </el-select>
                            </template>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :md="12" :sm="12" style="margin-bottom: 10px;">
                        <el-form-item label="时间段:">
                            <el-date-picker
                                v-model="saleSearch.datetime" 
                                type="daterange" 
                                range-separator="至" 
                                start-placeholder="开始日期" 
                                end-placeholder="结束日期">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :md="12" :sm="12" style="margin-bottom: 10px;">
                        <el-form-item class="ele-text-right" label-width="50px">
                            <el-button type="primary" size="mini" @click="searchs" icon="el-icon-search" class="ele-btn-icon">搜索 </el-button>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>

        </el-card>
        <el-card>
            <el-popover
                placement="top-start"
                transition="fade-in-linear"
                trigger="hover"
                content="总成本">
                <el-button slot="reference">总成本</el-button>
            </el-popover>
            <span> = </span>
            <el-popover
                placement="top-start"
                trigger="hover"
                content="0.082$*件数">
                <el-button slot="reference">入库费</el-button>
            </el-popover>
            <span> + </span>
            <el-popover
                placement="top-start"
                trigger="hover"
                content="0.5$*订单数">
                <el-button slot="reference">订单处理费</el-button>
            </el-popover>
            <span> + </span>
            <el-popover
                placement="top-start"
                trigger="hover"
                content="0.5$*件数">
                <el-button slot="reference">分拣费</el-button>
            </el-popover>
            <span> + </span>
            <el-popover
                placement="top-start"
                trigger="hover"
                content="用重量和邮编核算">
                <el-button slot="reference">海外仓配送费</el-button>
            </el-popover>
            <span> + </span>
            <el-popover
                placement="top-start"
                trigger="hover"
                content="14.48¥*件数（将转换成美金）">
                <el-button slot="reference">头程</el-button>
            </el-popover>
            <span> + </span>
            <el-popover
                placement="top-start"
                trigger="hover"
                content="采购成本（运营填入系统）">
                <el-button slot="reference">采购成本</el-button>
            </el-popover>
            <span> + </span>
            <el-popover
                placement="top-start"
                trigger="hover"
                content="0.15$*订单数（订单件数>=2时才会统计）">
                <el-button slot="reference">包装费</el-button>
            </el-popover>
        </el-card>
        <el-card>
            <el-popover
                placement="top-start"
                transition="fade-in-linear"
                trigger="hover"
                content="面板销售额">
                <el-button slot="reference">面板销售额</el-button>
            </el-popover>
            <span> = </span>
            <el-popover
                placement="top-start"
                trigger="hover"
                content="订单销售额">
                <el-button slot="reference">订单销售额</el-button>
            </el-popover>
            <span> + </span>
            <el-popover
                placement="top-start"
                trigger="hover"
                content="平台折扣">
                <el-button slot="reference">平台折扣</el-button>
            </el-popover>
            <span> + </span>
            <el-popover
                placement="top-start"
                trigger="hover"
                content="运费折扣">
                <el-button slot="reference">运费折扣</el-button>
            </el-popover>
            <span> - </span>
            <el-popover
                placement="top-start"
                trigger="hover"
                content="税费">
                <el-button slot="reference">Taxes</el-button>
            </el-popover>
            <span> - </span>
            <el-popover
                placement="top-start"
                trigger="hover"
                content="结算手续费,收货15天之后才有">
                <el-button slot="reference">结算手续费</el-button>
            </el-popover>
            <span> - </span>
            <el-popover
                placement="top-start"
                trigger="hover"
                content="退款金额">
                <el-button slot="reference">退款</el-button>
            </el-popover>
        </el-card>
        <el-card>
            <el-popover
                placement="top-start"
                transition="fade-in-linear"
                trigger="hover"
                content="实际盈利">
                <el-button slot="reference">实际盈利</el-button>
            </el-popover>
            <span> = </span>
            <el-popover
                placement="top-start"
                trigger="hover"
                content="面板销售额">
                <el-button slot="reference">面板销售额</el-button>
            </el-popover>
            <span> - </span>
            <el-popover
                placement="top-start"
                trigger="hover"
                content="面板广告费">
                <el-button slot="reference">面板广告费</el-button>
            </el-popover>
            <span> - </span>
            <el-popover
                placement="top-start"
                trigger="hover"
                content="总成本">
                <el-button slot="reference">总成本</el-button>
            </el-popover>
            <span> （ </span>
            <el-popover
                placement="top-start"
                trigger="hover"
                content="除开‘已取消’状态的所有订单">
                <el-button slot="reference">订单数</el-button>
            </el-popover>
            <el-popover
                placement="top-start"
                trigger="hover"
                content="统计所有SKU件数">
                <el-button slot="reference">件数</el-button>
            </el-popover>
            <el-popover
                placement="top-start"
                trigger="hover"
                content="订单中SKU数>=2的所有订单">
                <el-button slot="reference">(>=2件)单量</el-button>
            </el-popover>
            <span> ） </span>
        </el-card>

        <el-card shadow="always" body-style="padding:0 20px;" v-loading="loading" >
            <el-divider class="mt5 mb5" />
            <el-row>
                    <template>
                        <el-table
                        :data="arr_summary"
                        border
                        :default-sort = "{prop: 'date', order: 'descending'}"
                        style="width: 100%">
                                <el-table-column
                                    prop="total_amounts"
                                    label="总销售额$">
                                </el-table-column>
                                <el-table-column
                                    prop="advertisements"
                                    label="总广告消耗$">
                                </el-table-column>
                                <el-table-column
                                    prop="refund_fee"
                                    label="退款$">
                                </el-table-column>
                        </el-table>
                    </template>
            </el-row>
        </el-card>

        <el-card shadow="always" body-style="padding:0 20px;" v-loading="loading" >
            <el-divider class="mt5 mb5" />
            <el-row>
                    <div>店铺业绩</div>
                    <el-divider class="mt5 mb5" />
                    <template>
                        <el-table
                        :data="shopify_sales"
                        border
                        :summary-method="getSummaries"
                        show-summary
                        :row-class-name="tableRowClassName"
                        :cell-style="columnStyle"
                        :default-sort = "{prop: 'date', order: 'descending'}"
                        style="width: 100%">
                        <el-table-column
                                    prop="site_name"
                                    label="店铺">
                                </el-table-column>
                                <el-table-column
                                    prop="count"
                                    sortable
                                    label="订单数">
                                </el-table-column>
                                <el-table-column
                                    prop="storage"
                                    sortable
                                    label="件数">
                                </el-table-column>
                                <el-table-column
                                    prop="total_amounts"
                                    label="面板销售额$"
                                    sortable>
                                </el-table-column>
                                <el-table-column
                                    prop="advertisement"
                                    label="面板广告费$"
                                    sortable>
                                </el-table-column>
                                <el-table-column
                                    prop="roi"
                                    label="ROI"
                                    sortable>
                                </el-table-column>
                                <el-table-column
                                    prop="profit"
                                    label="实际盈利$"
                                    sortable>
                                </el-table-column>
                                <el-table-column
                                    prop="storage_fee"
                                    sortable
                                    label="入库费">
                                </el-table-column>
                                <el-table-column
                                    prop="processing_fee"
                                    sortable
                                    label="订单处理费">
                                </el-table-column>
                                <el-table-column
                                    prop="sorting_fee"
                                    sortable
                                    label="分拣费">
                                </el-table-column>
                                <el-table-column
                                    prop="shipping_fee"
                                    sortable
                                    label="海外仓配送费">
                                </el-table-column>
                                <el-table-column
                                    prop="cephalic_process"
                                    label="头程$"
                                    sortable>
                                </el-table-column>
                                <el-table-column
                                    prop="purchase"
                                    label="采购成本$"
                                    sortable>
                                </el-table-column>
                                <el-table-column
                                    prop="packaging_fee"
                                    sortable
                                    label="包装费">
                                </el-table-column>
                                <el-table-column
                                    prop="material_packaging_order"
                                    sortable
                                    label="(>=2件)单量">
                                </el-table-column>
                                <el-table-column
                                    prop="total_amount"
                                    sortable
                                    label="销售额$">
                                </el-table-column>
                                <el-table-column
                                    prop="platform_discount"
                                    sortable
                                    label="平台折扣$">
                                </el-table-column>
                                <el-table-column
                                    prop="shipping_fee_platform_discount"
                                    sortable
                                    label="运费折扣$">
                                </el-table-column>
                                <el-table-column
                                    prop="tax"
                                    sortable
                                    label="Taxes$">
                                </el-table-column>
                                <el-table-column
                                    prop="referral_fee_amount"
                                    sortable
                                    label="平台手续费">
                                </el-table-column>
                                <el-table-column
                                    prop="refund_fee"
                                    sortable
                                    label="退款费">
                                </el-table-column>
                                <el-table-column label="操作" align="left">
                                    <template slot-scope="scope">
                                        <el-button type="primary" plain size="mini" v-loading="exportLoading" @click="download_achievement(scope.row)">导出</el-button>
                                        <!-- <el-button class="btn-mar" size="mini" type="primary" @click="handleEdit(scope.row)">详情</el-button> -->
                                    </template>
                                </el-table-column>
                        </el-table>
                    </template>
            </el-row>
        </el-card>
        <!-- 编辑弹窗 -->
        <el-dialog :title="!disabled ? '编辑' : '详情'" :visible="editOpen"  :before-close="beforeClose" destroy-on-close>
            <EditForm ref="editForm" :findFormData="findFormData"  :disabled="disabled" @submitForm="submitForm" :editFormParams="editFormParams" @editFormCancel="beforeClose" />
        </el-dialog>

    </div>
</template>

<script>
import { curdMixin } from '@/mixins/curdMixin'
import EditForm from './EditFormCom'
import { mapGetters } from 'vuex'
export default {
    name: 'dashboardshop',
    mixins: [curdMixin],
    components: { EditForm},
    data() {
        return {
            site_arr: [],
            loading: false,
            pickerOptions: {
                shortcuts: [{
                    text: '最近一周',
                    onClick(picker) {
                    const end = new Date();
                    const start = new Date();
                    start.setTime(start.getTime() - 3600 * 1000 * 24 * 7 - 3600 * 1000 * 16);
                    end.setTime(end.getTime() - 3600 * 1000 * 16);
                    picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '最近一个月',
                    onClick(picker) {
                    const end = new Date();
                    const start = new Date();
                    start.setTime(start.getTime() - 3600 * 1000 * 24 * 30 - 3600 * 1000 * 16);
                    end.setTime(end.getTime() - 3600 * 1000 * 16);
                    picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '最近三个月',
                    onClick(picker) {
                    const end = new Date();
                    const start = new Date();
                    start.setTime(start.getTime() - 3600 * 1000 * 24 * 90 - 3600 * 1000 * 16);
                    end.setTime(end.getTime() - 3600 * 1000 * 16);
                    picker.$emit('pick', [start, end]);
                    }
                }]
            },
            saleSearch: {
                site_id: [],
                dateType: 1,
                datetime: '',
            },
            time: 0,
            start_time: new Date(),
            end_time: new Date(),
            us_time: 0,
            eur_time: 0,
            // 接口地址
            api: {
                edit: `/admin/datapanel/dashboard_new_edit`,
            },
            editFormParams: {
            },
            day_changes:0,
            sales_handle:'',
            paid_handle:'',
            gross_profit_handle:'',
            post_start_time:'',
            post_end_time:'',

            // 查询表单数据
            findFormData: {},
            // 是否展示编辑
            editOpen: false,

            arr_summary:[],
            shopify_sales:[
                {
                    material_packaging_order: '0',
                    packaging_fee: '0',
                    purchase: '0',
                    cephalic_process: '0',
                    shipping_fee: '0',
                    sorting_fee: '0',
                    processing_fee: '0',
                    storage_fee: '0',
                    refund_fee: '0',
                    referral_fee_amount: '0',
                    advertisement: '0',
                    tax: '0',
                    count: '0',
                    logistics: '0',
                    shipping_fee_platform_discount: '0',
                    original_total_product_price: '0',
                },
            ],
        }
    },
    computed: {
        ...mapGetters(['avatar', 'nickname', 'groups_name']),
    },
    created() {
        this.now();
        this.site();
        this.day_change(1);
    },
    methods: {
        // 导出
        download_achievement(row) {
            if(this.start_time == undefined || this.end_time == undefined){
                let start_time2 = new Date()
                start_time2.setTime(start_time2.getTime() - 3600 * 1000 * 24 * 1);
                this.start_time = start_time2;
                this.end_time = new Date();
            }
            let start_time = Date.parse(new Date(this.start_time));
            let end_time = Date.parse(new Date(this.end_time));
            start_time = Math.round(start_time)/1000;
            end_time = Math.round(end_time)/1000;
            
            this.loading = true
            const qyparams = {
                day_changes : this.day_changes,
                site_id : row.site_id,
                start_time : start_time,
                end_time : end_time
            }
            this.$confirm(`确定要下载销售明细吗?`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            })
                .then(() => {
                    return this.request.get('/admin/taskorder/download_achievement', { params: qyparams, responseType: 'blob' })
                })
                .then(response => {
                    this.download(response,'销售明细.xlsx')
                    this.$message.success('下载成功');
                })
                .catch(err => {})
                .finally(() => {
                    this.loading = false
                })
        },
        // 北京时间
        now() {
            this.us_time = new Date().getTime() - 16 * 3600 * 1000;
            setInterval(() => {
                this.us_time = new Date().getTime() - 16 * 3600 * 1000;
            }, 1000)
            this.eur_time = new Date().getTime() - 6 * 3600 * 1000;
            setInterval(() => {
                this.eur_time = new Date().getTime() - 6 * 3600 * 1000;
            }, 1000)
        },
        searchs() {
            this.saleSearch.dateType = -1;
            this.day_changes = 101;
            if(this.saleSearch.datetime == undefined || this.saleSearch.datetime == null || this.saleSearch.datetime == ''){
                this.$message.error('请筛选时间');
                return false;
            }else{
                this.start_time = this.saleSearch.datetime[0]
                this.end_time = this.saleSearch.datetime[1]
            }
            this.handleSkuFind();
        },
        select_change(val) {
            this.handleSkuFind();
        },
        day_change(val) {
            this.saleSearch.datetime = '';
            if(val == 0){
                this.saleSearch.dateType = -1;
                this.$message('未生成今日报表');
                return false;
            }
            let start_time2 = new Date();
            if(val == 0){
                this.start_time.setTime(start_time2.getTime() - 16 * 3600 * 1000);
                this.end_time.setTime(start_time2.getTime() + 9 * 3600 * 1000);
            }else if(val == 1){
                this.start_time.setTime(start_time2.getTime() - 3600 * 1000 * 24 - 16 * 3600 * 1000);
                this.end_time.setTime(start_time2.getTime() - 16 * 3600 * 1000);
            }else if(val == 2){
                this.start_time.setTime(start_time2.getTime() - 3600 * 1000 * 24 * 7 - 16 * 3600 * 1000);
                this.end_time.setTime(start_time2.getTime() - 16 * 3600 * 1000);
            }else if(val == 3){
                this.start_time.setTime(start_time2.getTime() - 16 * 3600 * 1000);
                this.end_time.setTime(start_time2.getTime() - 16 * 3600 * 1000);
            }
            this.day_changes = val;
            this.handleSkuFind();
        },
        
        async site() {
            let response = await this.request.post('/admin/datapanel/dashboard_site', {})
            if(response.code == 1){
                this.site_arr = response.data;
            }
        },
        // sku生成回显
        async handleSkuFind() {
            if(this.start_time == undefined || this.end_time == undefined){
                let start_time2 = new Date()
                start_time2.setTime(start_time2.getTime() - 3600 * 1000 * 24 * 1);
                this.start_time = start_time2;
                this.end_time = new Date();
            }
            let start_time = Date.parse(new Date(this.start_time));
            let end_time = Date.parse(new Date(this.end_time));
            start_time = Math.round(start_time)/1000;
            end_time = Math.round(end_time)/1000;
            this.loading = true;
            let response = await this.request.post('/admin/datapanel/dashboard_shop', { 
                day_changes : this.day_changes,
                site_id : this.saleSearch.site_id,
                start_time : start_time,
                end_time : end_time
            })
            this.loading = false;
            if(response.code == 1){
                this.shopify_sales = response.data.shopify_sales;
                this.arr_summary = response.data.arr_summary;
                this.post_start_time = response.data.start_time;
                this.post_end_time = response.data.end_time;
            }else{
                this.shopify_sales = [];
                this.arr_summary = [];
                this.post_start_time = '';
                this.post_end_time = '';
            }
            
        },

        
        getSummaries(param) {
            const { columns, data } = param;
            const sums = [];
            columns.forEach((column, index) => {
                if (index === 0) {
                    sums[index] = '统计';
                    return;
                }
                const values = data.map(item => Number(item[column.property]));
                if (!values.every(value => isNaN(value))) {
                    sums[index] = values.reduce((prev, curr) => {
                    const value = Number(curr);
                    if (!isNaN(value)) {
                        return prev + curr;
                    } else {
                        return prev;
                    }
                    }, 0);
                    if(index === 5){
                        sums[index] = '';
                    }else{
                        sums[index] = sums[index].toFixed(2);
                    }
                } else {
                    sums[index] = 'N/A';
                }
            });
            return sums;
        },
        // 表格列背景色
        columnStyle({ row, column, rowIndex, columnIndex }) {

        },
        // 表格行背景色
        tableRowClassName({ row, rowIndex }) {

        },
        // 编辑
        handleEdit(row) {
            this.handleFind(row.site_id)
        },

        // 编辑回显
        async handleFind(id) {
            let response = await this.request.get(this.api.edit, { params: 
                {
                    post_start_time:this.post_start_time,
                    post_end_time:this.post_end_time,
                    id:id,
                } })
            this.findFormData = this.formatFindData(response.data)
            this.editOpen = true
        },
    },
}
</script>

<style lang="scss" scoped>
.app-container {
    background: #f0f2f5;
    .title-tip {
        color: #909399;
        margin: 0;
        display: block;
    }
    /* 统计卡片 */
    .chart-card {
        color: #606266;
        margin-bottom: 15px;
    }
    .chart-card-num {
        font-size: 30px;
    }

    .chart-card-content {
        height: 50px;
        box-sizing: border-box;
        margin-bottom: 12px;
        font-size: 13px;
    }

    .chart-card-text {
        font-size: 13px;
    }
}
</style>
